<?php
ini_set('memory_limit','1024M');
//ini_set('display_errors', '0');
//error_reporting(E_ALL ^ E_STRICT);

/**
* Script for creating and loading database
*/

// Allow easy console colloring
require_once 'Console/Color.php';
 
// Initialize the application path and autoloading
$dirname = getcwd();

defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath($dirname . '/../www/application'));

set_include_path(implode(PATH_SEPARATOR, array(
    APPLICATION_PATH . '/../www/library',
    get_include_path(),
)));

require_once 'Zend/Console/Getopt.php';
require_once 'Zend/Json.php';
 
// Define some CLI options
$getopt = new Zend_Console_Getopt(array(
   'env|e-s'      => 'Application environment for which to create model s(defaults to development)',
   'overwrite|o'  => 'Overwrite disabled images if they exist.  This option will slow down the script if disabled images already exist.',
   'help|h'       => 'Help -- usage message',
));

try
{
    $getopt->parse();
}
catch (Zend_Console_Getopt_Exception $e)
{
    // Bad options passed: report usage
    echo $e->getUsageMessage();
    return false;
}
 
// If help requested, report usage message
if ($getopt->getOption('h'))
{
    echo $getopt->getUsageMessage();
    return true;
}
 
// Initialize values based on presence or absence of CLI options
$env      = $getopt->getOption('e');
if($env === null)
   $env = get_current_user();
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (null === $env) ? 'development' : $env);
 
echo 'Using APPLICATION_ENV = ' . APPLICATION_ENV . PHP_EOL;

$tableName = $getopt->getOption('t');

$jsonStoreObj = array(
   'identifier' => 'uid',
   'label' => 'name',
   'items' => array()
);

$pathToIconInfoHash = [];

$contentArray = array();
echo APPLICATION_PATH . '/../public/images/icons/' . PHP_EOL;
digestFolder(APPLICATION_PATH . '/../public/images/icons/', $jsonStoreObj, $pathToIconInfoHash, $contentArray, $getopt->getOption('o'));

echo APPLICATION_PATH . '/../public/css/iconStore.js' . PHP_EOL;
file_put_contents(APPLICATION_PATH . '/../public/css/iconStore.js', Zend_Json::encode($jsonStoreObj));
echo APPLICATION_PATH . '/../public/css/icons.json' . PHP_EOL;
file_put_contents(APPLICATION_PATH . '/../public/css/icons.json', Zend_Json::encode($pathToIconInfoHash));

// put css instructions into files
$i = 0;
$y = 1;
$cssInstructionIndex = 1;
$cssFileContent = '';
$files = array();
foreach($contentArray as $cssInstruction)
{
   $cssFileContent .= $cssInstruction;
   if($cssInstructionIndex % 4094 === 0 || $cssInstructionIndex >= count($contentArray))
   {
      // put the content into the file
      $filepath = APPLICATION_PATH . '/../public/css/sprites/spritesheet-'. str_pad($y++, 2, '0', STR_PAD_LEFT) .'.css';
      $files[] = $filepath;
      file_put_contents($filepath, $cssFileContent);
      if(file_exists("/wv/sdm/development/tools/yahoo/latest"))
      {
         exec("java -jar /wv/sdm/development/tools/yahoo/latest " . $filepath . " -o " . $filepath);
      }
      $cssFileContent = '';
   }
   $cssInstructionIndex++;
}

function digestFolder($path, & $jsonStoreObj, & $pathToIconInfoHash, & $contentArray, $overwrite, $currentLevel = '')
{
   if(!is_dir($path))
   {
      echo Console_Color::convert('%rCould not load path:%n "$path"%r.  It does not exist.%n') . PHP_EOL;
      return;
   }
   
   $imageCount = 0;
   $imageGenerationCount = 0;
   $jsonIconsArray = array();
   $files = listdir($path);
   sort($files, SORT_LOCALE_STRING);
   $maxWidth = 32767;   // Fire fox bug doesn't allow images greater an this size: https://bugzilla.mozilla.org/show_bug.cgi?id=591822
   $maxHeight = 32767;
   $widthAccumulator = 0;
   $heightAccumulator = 0;
   $widthAccumulatorMax = 0;
   $images = array();
   foreach($files as $file)
   {
      // Don't do hidden files - or ., .. dirrectories
      if(substr($file, 0, 1) == '.')
         continue;
      
      if(is_dir($path . $file))
         continue;
      else if(!is_file($path . $file))
         continue;
      
      $strippedFile = substr($file, -4);
      if($strippedFile != '.png')
         continue;
      
      $imageCount++;
      $strippedFile = basename($file, '.png');
      $shortCssName = str_replace('/', '-', $currentLevel);
      
      list($width, $height, $type, $attr) = getimagesize($path . $file);
      
      $cssName = "icons-$shortCssName$strippedFile";
      $cssPath = "/images/icons/$currentLevel$file";
      $cssDisabledPath = "/images/icons/$currentLevel/.disabled/$file";
      $uidPath = "icons/$currentLevel$file";
      if(!file_exists("$path/.disabled/"))
         mkdir("$path/.disabled/", 0755);
         
      // Make disabled version of file
      // eg. convert source.jpg -colorspace Gray destination.jpg
      $disabledImageFullPath = "$path/.disabled/$file";
      $disabledImageGenerated = false;
      $output = "";
      $retval = 0;
      if($overwrite || !file_exists($disabledImageFullPath))
      {
         exec("convert \"$path/$file\" -colorspace Gray \"$disabledImageFullPath\" 2>&1", $output, $retval);
         $disabledImageGenerated = true;
         $imageGenerationCount++;
      }
      $widthNeeded = $width;
      if($retval !== 0)
      {
         $disabledImageGenerated = false;
         echo Console_Color::convert('%rError converting file:%n') . PHP_EOL;
         var_dump($output);
      }
      else
      {
         $widthNeeded *= 2;
         $disabledImageGenerated = true;
      }

      $img = imagecreatefrompng($path . $file);
      $imgDisabled = null;
      if($disabledImageGenerated)
         $imgDisabled = @imagecreatefrompng($path . '/.disabled/' . $file);
      $left = '';
      $leftDisabled = '';
      $top = '';
      $cssPropertyTitle = 'background-image';
      if($img)
      {
         if(($widthAccumulator + ($widthNeeded)) > $maxWidth)
         {
            $heightAccumulator += $height;
            $widthAccumulatorMax = $widthAccumulator;
            $widthAccumulator = 0;
         }
         $cssPropertyTitle = 'background';
         $cssPath = "/css/sprites/spritesheet-" . $shortCssName . "01.png";
         $cssDisabledPath = $cssPath;
         $left = '-'.$widthAccumulator.'px';
         $leftDisabled = '-'.($widthAccumulator + $width).'px';
         $top = '-'.$heightAccumulator.'px';
         $images[] = array(
            'width'                    => $width,
            'height'                   => $height,
            'heightAccumulator'        => $heightAccumulator,
            'widthAccumulator'         => $widthAccumulator,
            'image'                    => $img,
            'imageDisabled'            => $imgDisabled
         );
         $widthAccumulator += $widthNeeded;
      }
      
      $contentArray[] = ".$cssName { width: ".$width."px; height: ".$height."px; $cssPropertyTitle: url($cssPath) $left $top; }" . PHP_EOL;
      if($disabledImageGenerated)
         $contentArray[] = ".dijitDisabled .$cssName { width: ".$width."px; height: ".$height."px; $cssPropertyTitle: url($cssDisabledPath) $leftDisabled $top }" . PHP_EOL;
      
      $jsonIconsArray[] = array(
         'name' => $strippedFile,
         'uid' => $uidPath,
         'type' => 'icon',
         'css' => $cssName,
         'width' => $width,
         'height' => $height,
         'left' => $left,
         'top' => $top,
         'path' => $cssPath,
         'disabledPath' => $cssDisabledPath,
         'hasDisabled' => $disabledImageGenerated);

      $iconInfo = array('width' => $width, 'height' => $height, 'spriteSheetPath' => $cssPath, 'normal' => array('left' => $left, 'top' => $top));
      if($disabledImageGenerated)
         $iconInfo['disabled'] = array('left' => $leftDisabled, 'top' => $top);
      $pathToIconInfoHash[$path . $file] = $iconInfo;
   }
   $heightAccumulator += 16;

   if(count($images) > 0)
   {
      if($widthAccumulatorMax < $widthAccumulator)
         $widthAccumulatorMax = $widthAccumulator;
      
      $spriteImage = imagecreatetruecolor($widthAccumulatorMax, $heightAccumulator);
      imagealphablending($spriteImage, false);
      imagesavealpha($spriteImage, true);
      foreach($images as $imageInfo)
      {
         imagecopy($spriteImage, $imageInfo['image'], $imageInfo['widthAccumulator'], $imageInfo['heightAccumulator'], 0, 0, $imageInfo['width'], $imageInfo['height']);
         imagedestroy($imageInfo['image']);
         if($imageInfo['imageDisabled'])
         {
            imagecopy($spriteImage, $imageInfo['imageDisabled'], $imageInfo['widthAccumulator'] + $imageInfo['width'], $imageInfo['heightAccumulator'], 0, 0, $imageInfo['width'], $imageInfo['height']);
            imagedestroy($imageInfo['imageDisabled']);
         }
      }
      imagepng($spriteImage, APPLICATION_PATH . "/../public/css/sprites/spritesheet-" . $shortCssName . "01.png");
      imagedestroy($spriteImage);
   }

   if($currentLevel != '' && count($jsonIconsArray) > 0)
      $jsonStoreObj['items'][] = array(
         'name' => $currentLevel,
         'uid'  => $currentLevel,
         'type' => 'category',
         'children' => $jsonIconsArray);
   if($imageCount > 0)
   {
      echo Console_Color::convert("%mCurent Level: %n" . $currentLevel . "%n") . PHP_EOL;
      echo Console_Color::convert("%c\tOriginal Image Count:%n       $imageCount") . PHP_EOL;
      echo Console_Color::convert("%c\tImage Generation Count:%n     $imageGenerationCount") . PHP_EOL;
   }
   
   // Now do all the directories...
   reset($files);
   foreach($files as $file)
   {
      // Don't do hidden files - or ., .. dirrectories
      if(substr($file, 0, 1) == '.')
         continue;

      if(is_dir($path . $file))
         digestFolder($path . $file . '/', $jsonStoreObj, $pathToIconInfoHash, $contentArray, $overwrite, $currentLevel . $file . '/');
   }
}

// http://php.net/manual/en/function.readdir.php
// post: frasq at frasq dot org 01-Nov-2010 03:46
function listdir($dir='.') { 
    if (!is_dir($dir)) { 
        return false; 
    } 
    
    $files = array(); 
    listdiraux($dir, $files); 

    return $files; 
} 

function listdiraux($dir, &$files) { 
    $handle = opendir($dir); 
    while (($file = readdir($handle)) !== false) { 
        if ($file == '.' || $file == '..') { 
            continue; 
        } 
        $filepath = $dir == '.' ? $file : $dir . '/' . $file; 
        //if (is_link($filepath)) 
        //    continue; 
        $files[] = $file; 
    } 
    closedir($handle); 
} 
